package com.iasku.iaskueleclass_phone.activity;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.iasku.constant.Constant;
import com.iasku.constant.IntentConfig;
import com.iasku.iaskueleclass_phone.R;

public class VideoPlayActivity extends BaseActivity

implements OnCompletionListener, OnErrorListener, OnInfoListener,

OnPreparedListener, OnSeekCompleteListener, OnVideoSizeChangedListener,

SurfaceHolder.Callback {
    Display currentDisplay;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    MediaPlayer mediaPlayer;// 使用的是MediaPlayer来播放视频
    int videoWidth = 0; // 视频的宽度，初始化，后边会对其进行赋值
    int videoHeight = 0;
    int screenWidth, screenHeight, progress = 0;// 同上
    ImageButton start_btn;
    boolean readyToPlayer = false;
    LinearLayout L_play;
    private String filePath = "此处存放播放地址";// 本地地址和网络地址都可以
    public final static String LOGCAT = "CUSTOM_VIDEO_PLAYER";
    public static SeekBar seekBar = null;
    public static TextView timetextview = null;
    private TextView timetextview2;
    Thread thread = null;
    Boolean cansendmessage;
    PowerManager powerManager = null;
    WakeLock wakeLock = null;
    private Thread doThread;
    private String questionno;

    private int playtime;

    private void init() {
        // filePath = "http://iasku.517idc.com:189/videos/"
        // + getIntent().getStringExtra(Constants.FILE_PATH);
        initTitleBar();
        mProgressDialog.setMessage("");
        mProgressDialog.show();
        surfaceView = (SurfaceView) findViewById(R.id.SurfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mediaPlayer = new MediaPlayer();

        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnSeekCompleteListener(this);
        mediaPlayer.setOnVideoSizeChangedListener(this);
        cansendmessage = true;
        filePath = getIntent().getStringExtra(IntentConfig.QUE_VIDEO_PATH);
        System.out.println("filePath=》" + filePath);
        // System.out.println("playtime="+playtime);
        // // System.out.println(filePath);
        // //
        // filePath="http://iasku.517idc.com:189/videos/22249_dengjingdong.mp4";

        L_play = (LinearLayout) findViewById(R.id.L_play);
        // L_play.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,
        // screenHeight));
        start_btn = (ImageButton) findViewById(R.id.start_btn);
        start_btn.setOnClickListener(new myOnClickListener());
        timetextview = (TextView) findViewById(R.id.time_textview);
        timetextview2 = (TextView) findViewById(R.id.time_textview2);
        seekBar = (SeekBar) findViewById(R.id.seekBarId);
        seekBar.setMax(100);
        seekBar.setOnSeekBarChangeListener(new MyOnseekBarChangeListener());
        thread = new Thread(null, updatesb, "updatesb");
        powerManager = (PowerManager) this
                .getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");
        wakeLock.setReferenceCounted(false);
        wakeLock.acquire();

        doThread = new Thread(setmediaplay);
        doThread.start();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels - 50;
        setContentView(R.layout.videoplay);
        init();
    }

    class myOnClickListener implements OnClickListener {
        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.start_btn:
                Drawable drawable = null;// 开始/暂停
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    drawable = getResources().getDrawable(R.drawable.start);
                } else {
                    mediaPlayer.start();
                    drawable = getResources().getDrawable(R.drawable.pause1);
                }
                start_btn.setBackgroundDrawable(drawable);
                break;
            default:
                break;

            }
        }
    }

    private Runnable setmediaplay = new Runnable() {

        public void run() {
            try {
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.prepare();
                Message msgMessage = new Message();

                msgMessage.what = 2;
                mHandler.sendMessage(msgMessage);
            } catch (IllegalArgumentException e) {
                finish();
            } catch (IllegalStateException e) {
                finish();
            } catch (IOException e) {
                finish();
            }

        }

    };

    class MyOnseekBarChangeListener implements OnSeekBarChangeListener {

        // 当用户结束对滑块滑动时,调用该方法
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.start();
        }

        // 当用户开始滑动滑块时调用该方法
        public void onStartTrackingTouch(SeekBar seekBar) {
            if (mediaPlayer.isPlaying()) { // 加个判断，防止出错
                mediaPlayer.pause();
            }
        }

        // 当进度条发生变化时调用该方法
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            if (seekBar.isPressed()) { // 按下进度条拖动时才不断更新时间
                mediaPlayer.seekTo(seekBar.getProgress()
                        * mediaPlayer.getDuration() / seekBar.getMax());
            }
        }
    }

    private Runnable updatesb = new Runnable() {

        public void run() {
            if (cansendmessage) {
                Message msgMessage = new Message();

                progress = (int) ((float) mediaPlayer.getCurrentPosition()
                        / mediaPlayer.getDuration() * 100);
                progress++;

                msgMessage.what = 1;
                mHandler.sendMessage(msgMessage);
            }

        }
    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            // 正在下载
            case 1:
                try {
                    SetSongTime();
                    SetSeekBar();
                    mHandler.postDelayed(updatesb, 100);
                } catch (Exception e) {
                }
                break;
            case 2:
                mProgressDialog.dismiss();
                if (!thread.isAlive()) {
                    thread.start();
                }
                break;
            }
        }
    };

    public void SetSongTime() {
        // 得到当前播放进度的分和秒，格式00:00
        String str1, str2;
        int Curren_fen = mediaPlayer.getCurrentPosition() / 1000 / 60;
        int Curren_miao = mediaPlayer.getCurrentPosition() / 1000 % 60;
        if (Curren_fen / 10 == 0)
            str1 = "0" + Curren_fen;
        else
            str1 = Curren_fen + "";
        if (Curren_miao / 10 == 0)
            str2 = "0" + Curren_miao;
        else
            str2 = Curren_miao + "";
        // 得到歌曲总时间长度的分和秒，格式00:00
        String str3, str4;
        int Duration_fen = mediaPlayer.getDuration() / 1000 / 60;
        int Duration_miao = mediaPlayer.getDuration() / 1000 % 60;
        if (Duration_fen / 10 == 0)
            str3 = "0" + Duration_fen;
        else
            str3 = Duration_fen + "";
        if (Duration_miao / 10 == 0)
            str4 = "0" + Duration_miao;
        else
            str4 = Duration_miao + "";
        // 在timetextview显示当前时间、总时间、当前歌曲、总歌曲数
        if (mediaPlayer.isPlaying()) {
            timetextview.setText(str1 + ":" + str2);
            timetextview2.setText(str3 + ":" + str4);
        }
    }

    // ===================================更新SeekBar进度条======================================
    public void SetSeekBar() {
        // 设置进度条
        int position = mediaPlayer.getCurrentPosition();
        // System.out.println("position=>"+mediaPlayer.getCurrentPosition());
        int mpMax = mediaPlayer.getDuration();
        // System.out.println("duration=>"+mpMax);
        int sbMax = seekBar.getMax();
        seekBar.setProgress(position * sbMax / mpMax);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if(mediaPlayer!=null)
            mediaPlayer.setDisplay(holder);// 若无次句，将只有声音而无图像

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer arg0, int arg1, int arg2) {
        Log.v(LOGCAT, "onVideoSizeChanged Called");
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {

        Log.v(LOGCAT, "onSeekComplete Called");
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        mp.start();
    }

    @Override
    public boolean onInfo(MediaPlayer arg0, int whatInfo, int extra) {
        if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
            Log.v(LOGCAT, "Media Info, Media Info Bad Interleaving " + extra);
        } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
            Log.v(LOGCAT, "Media Info, Media Info Not Seekable " + extra);
        } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
            Log.v(LOGCAT, "Media Info, Media Info Unknown " + extra);
        } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
            Log.v(LOGCAT, "MediaInfo, Media Info Video Track Lagging " + extra);
        } else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
            Log.v(LOGCAT, "MediaInfo, Media Info Metadata Update " + extra);
        }
        return false;
    }

    @Override
    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
        Log.v(LOGCAT, "onError Called");
        if (arg1 == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
            Log.v(LOGCAT, "Media Error, Server Died " + arg2);
        } else if (arg1 == MediaPlayer.MEDIA_ERROR_UNKNOWN) {

        }
        return false;
    }

    @Override
    public void onDestroy() {
        wakeLock.release();
        cansendmessage = false;
        if (doThread != null) {
            if (doThread.isAlive()) {
                doThread.interrupt();
            }
        }
        super.onDestroy();
        if (mediaPlayer.isPlaying()) {

            mediaPlayer.stop();
            mediaPlayer.release();
        }

    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        if (thread != null) {
            thread.interrupt();
        }
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
//      MobclickAgent.onPageStart("VideoPlayActivity");
//      MobclickAgent.onResume(this);
    }

}
